package com.epfresh.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.bean.LocalUploadFileEntity;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.DataManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class EnsureCompanyActivity extends BaseActivity implements PhotoCore.PhotoResult {

    private TextView areaEt;
    private EditText detailEt;
    private EditText name;
    private EditText edOrg;
    private TextView number;
    private RelativeLayout rlCompany;
    private View rlError;
    private View pbCompany;
    private ImageView company_pic;
    private RelativeLayout rlCompany2;
    private View rlError2;
    private View pbCompany2;
    private ImageView company_pic2;

    private ImageView currentIv;
    private Button sureBu;


    Context mContext;
    private int imgWidth;
    private int imgHeight;
    private PhotoCore photoCore;

    private String fileTogetherPath = FileUtil.getImgCacheDir() + "/" + "commpany";
    private String filePath = fileTogetherPath;

    private String fileFrPath = FileUtil.getImgCacheDir() + "/" + "commpany2";

    String provinceId = "";
    String cityId = "";
    String districtId = "";
    String provinceName = "";
    String cityName = "";
    String districtName = "";
    private String cityname;

    private View rlRefuse;
    private TextView tvRefuseContent;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ensurecompany);
        areaEt = (TextView) findViewById(R.id.area);
        detailEt = (EditText) findViewById(R.id.detail);
        company_pic = (ImageView) findViewById(R.id.company_pic);
        name = (EditText) findViewById(R.id.name);
        number = (TextView) findViewById(R.id.number);
        rlCompany = (RelativeLayout) findViewById(R.id.rl_company);
        rlError = findViewById(R.id.rl_error);
        pbCompany = findViewById(R.id.rl_pb);
        company_pic = (ImageView) findViewById(R.id.company_pic);
        sureBu = (Button) findViewById(R.id.sure);
        rlCompany2 = (RelativeLayout) findViewById(R.id.rl_company2);
        rlError2 = findViewById(R.id.rl_error2);
        pbCompany2 = findViewById(R.id.rl_pb2);
        company_pic2 = (ImageView) findViewById(R.id.company_pic2);

        rlRefuse = findViewById(R.id.rl_refuse_reason);
        tvRefuseContent = (TextView) findViewById(R.id.tv_refuse_content);

        rlRefuse.setVisibility(View.GONE);
        edOrg = (EditText) findViewById(R.id.ed_org);

        mContext = this;
        basetitle.setText("企业认证");
        baseback.setVisibility(View.VISIBLE);
        fileTogetherPath = fileTogetherPath + "_" + getUser().getAccountId();
        filePath = fileTogetherPath;
        fileFrPath = fileFrPath + "_" + getUser().getAccountId();

        imgWidth = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.designedDP2px(80));
        if (imgWidth > LocalDisplay.designedDP2px(160)) {
            imgWidth = LocalDisplay.designedDP2px(160);
        }
        imgHeight = imgWidth * 337 / 448;
        reSizeIv(rlCompany);
        reSizeIv(rlCompany2);

        photoCore = new PhotoCore(this, this);
        photoCore.setCrop(false);
        photoCore.setRatio(4, 3);
        photoCore.setRatio(4, 3);
        photoCore.setResultHeight(500);
        photoCore.setResultWidth(500);
//        loadImage(Uri.fromFile(new File(fileTogetherPath)).toString(), company_pic);
//        loadImage(Uri.fromFile(new File(fileFrPath)).toString(), company_pic2);

//        loadPicInfo();
//        updateInfo();
        areaEt.setOnClickListener(this);
        company_pic2.setOnClickListener(this);
        company_pic.setOnClickListener(this);
        sureBu.setOnClickListener(this);
        rightbtn.setText("帮助");
        rightbtn.setTextColor(0xff898989);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(this);
        requestCertificateRefuse();
    }

    public void reSizeIv(View iv) {
        ViewGroup.LayoutParams lp = iv.getLayoutParams();
        lp.height = imgHeight;
        lp.width = imgWidth;

        iv.setLayoutParams(lp);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.area:

                break;

            case R.id.company_pic:
                filePath = fileTogetherPath;
                currentIv = company_pic;
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)),filePath, rlError.getVisibility() != View.GONE);
                break;
            case R.id.company_pic2:
                filePath = fileFrPath;
                currentIv = company_pic2;
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)),filePath, rlError2.getVisibility() != View.GONE);
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.rightbtn:
                help();
                break;
            case R.id.sure:

                if (InputControl.isEmpty(name)) {
                    ToastUtils.TextToast(this, "请填写企业名称");
                    return;
                }
                if (!VerificationUtils.isValid(name.getText().toString())){
                    toast(getString(R.string.illegal_input,"企业名称"));
                    return;
                }
                if (InputControl.isEmpty(number)) {
                    ToastUtils.TextToast(this, "请填写营业执照编号");
                    return;
                }
                if (!VerificationUtils.isValid(number.getText().toString())){
                    toast(getString(R.string.illegal_input,"营业执照编号"));
                    return;
                }
                if (InputControl.isEmpty(edOrg)) {
                    ToastUtils.TextToast(this, "请填写法人手机");
                    return;
                }

                String s = edOrg.getText().toString();
                if (s.length() != 11 ){
                    ToastUtils.TextToast(this, "请输入合法的手机号");
                    return;
                }
                if (InputControl.isEmpty(detailEt)) {
                    ToastUtils.TextToast(this, "请填写法人姓名");
                    return;
                }
                if (!VerificationUtils.isValid(detailEt.getText().toString())){
                    toast(getString(R.string.illegal_input,"法人姓名"));
                    return;
                }
                if (picId == null || "".equals(picId)) {
                    ToastUtils.TextToast(this, "请上传营业执照副本");
                    return;
                }

                requestCertificate();


                break;
        }
    }

    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_HELP_CERTIFY);
        intent.putExtra(Constant.KEY_WEB_TITLE, "帮助");
        startActivity(intent);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == 1) {
            // 回传城市名字 城市ID
            if (intent != null) {
                cityname = intent.getExtras().getString("name");
                provinceId = intent.getStringExtra("provinceCode");
                cityId = intent.getStringExtra("cityCode");
                districtId = intent.getStringExtra("areaCode");
                areaEt.setText(cityname);
                return;
            }
            return;
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }
        photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    String picId = "";
    String picId2 = "";

    DisplayImageOptions displayImageOptions;

    private DisplayImageOptions getImageOption() {
        if (displayImageOptions == null)
            displayImageOptions = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中

                    .cacheOnDisk(false)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//
                    // 设置图片以如何的编码方式显示
                    .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                    // .decodingOptions(new Options())//设置图片的解码配置
                    // .delayBeforeLoading(int delayInMillis)//int
                    // delayInMillis为你设置的下载前的延迟时间
                    // 设置图片加入缓存前，对bitmap进行设置
                    // .preProcessor(BitmapProcessor preProcessor)
                    .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                    .build();// 构建完成
        return displayImageOptions;
    }

    public void loadImage(String path, ImageView iv) {
        ImageSize imageSize = new ImageSize(imgWidth, imgHeight);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(iv), getImageOption(), imageSize, null, null);

    }

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:

                    break;
                case HttpRequest.FAIL_NO_NET:

                    break;
                case HttpRequest.FAIL_NET_FAULT:

                default:

                    break;
            }
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onStart(Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            showProgress(requestTag.action);
            hideError(requestTag.action);
        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }
            File f = null;
            switch (requestTag.action) {
                case R.id.company_pic:
                    picId = id + "";
                    f = new File(fileTogetherPath);
                    updatePicInfo(f, id, "company_img_" + getUser().getAccountId());
                    break;
                case R.id.company_pic2:
                    picId2 = id + "";
                    f = new File(fileFrPath);
                    updatePicInfo(f, id, "company_img_2" + getUser().getAccountId());
                    break;
                default:
                    break;
            }
        }
    };

    private void showProgress(int action) {
        switch (action) {
            case R.id.company_pic:
                pbCompany.setVisibility(View.VISIBLE);
                break;
            case R.id.company_pic2:
                pbCompany2.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void hideProgress(int action) {
        switch (action) {
            case R.id.company_pic:
                pbCompany.setVisibility(View.GONE);
                break;
            case R.id.company_pic2:
                pbCompany2.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void showError(int action) {
        switch (action) {
            case R.id.company_pic:
                rlError.setVisibility(View.VISIBLE);
                break;
            case R.id.company_pic2:
                rlError2.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void hideError(int action) {
        switch (action) {
            case R.id.company_pic:
                rlError.setVisibility(View.GONE);
                break;
            case R.id.company_pic2:
                rlError2.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    RequestTag tag = new RequestTag();

    public void uploadImage(String filePath, int id) {

        L.d("uploadfile", "-------" + SystemClock.currentThreadTimeMillis());
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
            data.setCmd(AppPurchaseRouterConstant.cmd_account_file_upload);
            //data.setToken(getUser().getToken());

           // data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);

            data.setParameters(map);


            tag.tag = AppPurchaseRouterConstant.cmd_account_file_upload;
            tag.action = id;
            request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OnRequestListener<StatusEntity> onResquestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
//            switch (failCode) {
//                case HttpRequest.FAIL_NOT_FOUND:
//
//                    break;
//                case HttpRequest.FAIL_NO_NET:
//
//                    break;
//                case HttpRequest.FAIL_NET_FAULT:
//
//                default:
//
//                    break;
//
//            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                toast(BaseApplication.getDoc().getBeenSubmitted());
                getUser().setCertStatus(1);
                updateUser(getUser());
                Intent intent = new Intent(mContext,
                        HomeActivity.class);
                intent.putExtra("home_tab_index", getIntent().getIntExtra("home_tab_index",0));
                mContext.startActivity(intent);
                //getUser().setCertStatus(1);
               // getStoreInfo().setCertType("2");
               // updateStoreInfo(getStoreInfo());
              /*  Intent intent = new Intent(getApplicationContext(),
                        StoreEnsureAndOpenActivity.class);
                intent.putExtra("type", "detail_order");
                startActivity(intent);*/
                finish();
            } else {

            }
        }
    };

    public void requestCertificate() {

        String nameStr = name.getText().toString();
        String numberStr = number.getText().toString();
        String orgCode = edOrg.getText().toString();

        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_enterpriseCert);
        //data.setToken(getUser().getToken());

        //data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();

        map.put("name", nameStr);
        map.put("accountId", getUser().getAccountId());
        map.put("licenceNo", numberStr);
        map.put("licenceImgId", picId);
        map.put("orgCodeImgId", picId2);
        map.put("legalPersonPhone", orgCode);
        map.put("legalPersonName", detailEt.getText().toString());

        map.put("address", areaEt.getText().toString() + detailEt.getText().toString());

        data.setParameters(map);

        request(data, AppPurchaseRouterConstant.cmd_account_acc_enterpriseCert, onResquestListener);
    }

    public void saveInfo() {
        String nameStr = name.getText().toString();
        String numberStr = number.getText().toString();
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("licenceNo_" + getUser().getAccountId(), numberStr);
        edit.putString("licenceName_" + getUser().getAccountId(), nameStr);


        String addressDetailStr = detailEt.getText().toString();
        String addressAreaStr = areaEt.getText().toString();

        edit.putString("licenceOrg_" + getUser().getAccountId(), edOrg.getText().toString());
        edit.putString("licenceArea_" + getUser().getAccountId(), addressAreaStr);
        edit.putString("licenceDetail_" + getUser().getAccountId(), addressDetailStr);
        edit.putString("licenceP_" + getUser().getAccountId(), provinceId);
        edit.putString("licenceC_" + getUser().getAccountId(), cityId);
        edit.putString("licenceD_" + getUser().getAccountId(), districtId);

        edit.commit();
    }

    public void updateInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String num = sp.getString("licenceNo_" + getUser().getAccountId(), "");
        String nameStr = sp.getString("licenceName_" + getUser().getAccountId(), "");
        number.setText(num);
        name.setText(nameStr);
        name.setSelection(nameStr.length());
        provinceId = sp.getString("licenceP_" + getUser().getAccountId(), "");
        cityId = sp.getString("licenceC_" + getUser().getAccountId(), "");
        districtId = sp.getString("licenceD_" + getUser().getAccountId(), "");
        areaEt.setText(sp.getString("licenceArea_" + getUser().getAccountId(), ""));
        detailEt.setText(sp.getString("licenceDetail_" + getUser().getAccountId(), ""));
        edOrg.setText(sp.getString("licenceOrg_" + getUser().getAccountId(), ""));
    }

    public void updatePicInfo(File f, int id, String key) {
        long lastModified = f.lastModified();
        long totalSpace = f.getTotalSpace();
        LocalUploadFileEntity localUploadFileEntity = new LocalUploadFileEntity();
        localUploadFileEntity.setId(id);
        localUploadFileEntity.setModified(lastModified);
        localUploadFileEntity.setTotalSpace(totalSpace);
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, localUploadFileEntity.toString());
        edit.commit();
    }

    private void loadPicInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String result = sp.getString("company_img_" + getUser().getAccountId(), "");

        picId = initPicId(result, fileTogetherPath, company_pic.getId());
        result = sp.getString("company_img_2" + getUser().getAccountId(), "");
        picId2 = initPicId(result, fileFrPath, company_pic2.getId());

    }

    private String initPicId(String result, String filePath, int id) {
        L.d("file", "" + filePath + "--result:" + result);
        File f = new File(filePath);
        if (!TextUtils.isEmpty(result)) {
            LocalUploadFileEntity localUploadFileEntity = LocalUploadFileEntity.getLocalUploadFileEntity(result);
            L.d("file", "---------");
            if (localUploadFileEntity != null) {

                boolean isUpload = localUploadFileEntity.isUpload(f.lastModified(), f.getTotalSpace());
                L.d("file", "1." + localUploadFileEntity.getModified() + "--" + localUploadFileEntity.getTotalSpace());
                L.d("file", "2." + f.lastModified() + "--" + f.getTotalSpace());
                if (isUpload) {
                    return localUploadFileEntity.getId() + "";
                }
            }
        }
        if (f.exists()) {
            showError(id);
        }

        return "";
    }


    @Override
    public void onSuccess(String path) {
        loadImage(path, currentIv);

        uploadImage(filePath, currentIv.getId());
    }

    @Override
    public void onFail(String msg) {
        toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        uploadImage(filePath, currentIv.getId());
    }

    @Override
    protected void onDestroy() {
        if (photoCore != null) {
            photoCore.onDestory();
        }
        RequestManager.getInstance().cancel(tag);
        RequestManager.getInstance().cancel("account/enterpriseCert");
//        saveInfo();
        super.onDestroy();
    }


    public void requestCertificateRefuse() {
        
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_certInfo);
        //data.setToken(getUser().getToken());

        RequestTag tag = new RequestTag();
        tag.type = RequestTag.TYPE_CURRENT;
        tag.tag = AppPurchaseRouterConstant.cmd_account_acc_certInfo;
       
        request(data, tag, new OnRequestListener<Map<String,String>>() {
            @Override
            public Map<String, String> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr,new TypeToken<Map<String,String>>(){}.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<Map<String, String>> response, Object tag) {

                Map<String, String> responseElement = response.getResponseElement();

//                "remark": "", 拒绝原因
//                "status": 1, 审核状态
//                "type": 2 认证类型
                if (responseElement != null){
                    String remark = responseElement.get("remark");
                    String type = responseElement.get("type");
                    if (remark != null &&"2".equals(type)){
                        tvRefuseContent.setText(remark);
                        rlRefuse.setVisibility(View.VISIBLE);
                    }
                }

            }
        });
    }




}

